﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Data;
using System.Data.Common;
using System.Text.RegularExpressions;
using System.IO;

using TRPOP.Common;
using TRPOP.Config;
using TRPOP.CMS.Model;

namespace TRPOP.CMS.Template
{
    /// <summary>
    /// 资源处理类
    ///  1 根据资源相对地址，转换为绝对地址
    ///  2 绝对地址可为多个绝对地址，如果绝对地址相对应的图片不存在，则进行压缩
    /// </summary>
    public class ImgResourceHelper
    {
        #region 全局变量

        /// <summary>
        /// 图片相对地址 与 绝对地址 的对应关系
        /// </summary>
        public Dictionary<string, Dictionary<ImgType.ImgResourceType, string>> oDicSource = new Dictionary<string, Dictionary<ImgType.ImgResourceType, string>>();

        /// <summary>
        /// 匹配所有的图片
        /// </summary>
        private const string strFindPicPattern = "[=][" + "\"" + @"'][\s]*(?<file>[/][\S]*[.]((png)|(bmp)|(jpg)|(jpeg)|(gif)|(psd)))[" + "\"" + "']";

        /// <summary>
        /// 匹配img标签里的width
        /// </summary>
        private static Regex oRegexImgWidth = new Regex(@"[<]img[\s\S]+?(?<width>width[=][" + "\"" + @"']\S+[" + "\"" + @"'])[\s\S]+?[/][>]", RegexOptions.IgnoreCase);

        /// <summary>
        /// 匹配img标签里的height
        /// </summary>
        private static Regex oRegexImgHeight = new Regex(@"[<]img[\s\S]+?(?<height>height[=][" + "\"" + @"']\S+[" + "\"" + @"'])[\s\S]+?[/][>]", RegexOptions.IgnoreCase);

        #endregion

        /// <summary>
        /// 将当前实体里的图片集合初始化为所需要的类别
        /// </summary>
        /// <param name="oImgResourceType"></param>
        private void Init(ImgType.ImgResourceType oImgResourceType)
        {
            if (oImgResourceType == ImgType.ImgResourceType.Iphone && SYSConfig.Mobile_IsMobile)
            {
                foreach (KeyValuePair<string, Dictionary<ImgType.ImgResourceType, string>> oKeyValuePair in oDicSource)
                {

                    string strSourcePhysic = TRPOP.Common.RequestHelper.GetMapPath(oKeyValuePair.Key);

                    if (oKeyValuePair.Value.ContainsKey(oImgResourceType) == false && FileUtil.IsExist(strSourcePhysic))
                    {
                        string strNormalURL = oKeyValuePair.Value[ImgType.ImgResourceType.Normal];
                        string strNewPath = strSourcePhysic.Insert(strSourcePhysic.LastIndexOf("."), SYSConfig.Mobile_ExtName);
                        if (File.Exists(strNewPath))
                        {
                            oDicSource[oKeyValuePair.Key].Add(ImgType.ImgResourceType.Iphone, strNormalURL.Insert(strNormalURL.LastIndexOf("."), SYSConfig.Mobile_ExtName));
                        }
                        else
                        {
                            using (System.IO.StreamReader strmReader = new System.IO.StreamReader(strSourcePhysic))
                            {
                                if (CKFinder.Connector.ImageTools.ResizeImage(strSourcePhysic, strNewPath, SYSConfig.Mobile_MaxWidth, SYSConfig.Mobile_MaxHeight, true, 80))
                                {
                                    oDicSource[oKeyValuePair.Key].Add(ImgType.ImgResourceType.Iphone, strNormalURL.Insert(strNormalURL.LastIndexOf("."), SYSConfig.Mobile_ExtName));
                                }
                            }
                        }
                    }

                    //如果还是不包含指定的类型，那么默认添加ImgType.ImgResourceType.Normal类型的图片
                    if (oKeyValuePair.Value.ContainsKey(oImgResourceType) == false)
                    {
                        oDicSource[oKeyValuePair.Key].Add(ImgType.ImgResourceType.Iphone, oKeyValuePair.Value[ImgType.ImgResourceType.Normal]);
                    }
                }
            }
        }

        /// <summary>
        /// 将数据源里已找到的相对的图片（这些图片已被转换为某种类型的绝对地址），将图片从某类型的绝对地址转换为另一个类型的绝对地址
        /// </summary>
        /// <param name="strContentSource"></param>
        /// <param name="oImgResourceType"></param>
        /// <returns></returns>
        public string GetSourceContent(string strContentSource, ImgType.ImgResourceType oImgResourceTypeFrom, ImgType.ImgResourceType oImgResourceTypeTo)
        {
            Init(oImgResourceTypeTo);
            foreach (KeyValuePair<string, Dictionary<ImgType.ImgResourceType, string>> oKeyValuePair in oDicSource)
            {
                if (oKeyValuePair.Value.ContainsKey(oImgResourceTypeFrom) && oKeyValuePair.Value.ContainsKey(oImgResourceTypeTo))
                {
                    strContentSource = strContentSource.Replace("\"" + oKeyValuePair.Value[oImgResourceTypeFrom] + "\"", "\"" + oKeyValuePair.Value[oImgResourceTypeTo] + "\"")
                                                       .Replace("'" + oKeyValuePair.Value[oImgResourceTypeFrom] + "'", "'" + oKeyValuePair.Value[oImgResourceTypeTo] + "'");
                }
            }
            return CheckContentImg(strContentSource, oImgResourceTypeTo);
        }

        #region 尚未用到的方法
        /// <summary>
        /// 根据图片相对地址得到图片绝对地址,这里获取的是PC版的地址
        /// </summary>
        /// <param name="strSource"></param>
        /// <returns></returns>
        public string GetImgURL(string strSource)
        {
            //初始值为原值 即： 如果查询不到，则返回原来的地址
            string strReturn = strSource;

            //如果查询到了，则返回查询的结果
            if (oDicSource.ContainsKey(strSource) && oDicSource[strSource].ContainsKey(ImgType.ImgResourceType.Normal))
            {
                strReturn = oDicSource[strSource][ImgType.ImgResourceType.Normal];
            }

            return strReturn;

        }
        /// <summary>
        /// 根据图片相对地址得到图片绝对地址
        /// </summary>
        /// <param name="strSource"></param>
        /// <param name="oImgResourceType"></param>
        /// <returns></returns>
        public string GetImgURL(string strSource, ImgType.ImgResourceType oImgResourceType)
        {
            //初始值为原值 即： 如果查询不到，则返回原来的地址
            string strReturn = strSource;

            //如果查询到了，则返回查询的结果
            if (oDicSource.ContainsKey(strSource) && oDicSource[strSource].ContainsKey(oImgResourceType))
            {
                strReturn = oDicSource[strSource][oImgResourceType];
            }

            return strReturn;

        }

        /// <summary>
        /// 将数据源里的所有的已找到的相对地址转换为指定类型的绝对地址
        /// </summary>
        /// <param name="strContentSource"></param>
        /// <param name="oImgResourceType"></param>
        /// <returns></returns>
        public string GetSourceContent(string strContentSource, ImgType.ImgResourceType oImgResourceType)
        {
            foreach (KeyValuePair<string, Dictionary<ImgType.ImgResourceType, string>> oKeyValuePair in oDicSource)
            {
                strContentSource = strContentSource.Replace("\"" + oKeyValuePair.Key + "\"", "\"" + oKeyValuePair.Value[ImgType.ImgResourceType.Normal] + "\"")
                                                   .Replace("'" + oKeyValuePair.Key + "'", "'" + oKeyValuePair.Value[ImgType.ImgResourceType.Normal] + "'");
            }
            return strContentSource;
        }

        /// <summary>
        /// 添加一个图片至当前图片集合里
        /// </summary>
        /// <param name="strSource"></param>
        /// <param name="strNormalURL"></param>
        private void SaveOneImg(string strSource, string strNormalURL)
        {
            if (oDicSource.ContainsKey(strSource) == false)
            {
                oDicSource.Add(strSource, new Dictionary<ImgType.ImgResourceType, string>());
                oDicSource[strSource].Add(ImgType.ImgResourceType.Normal, strNormalURL);
                //其它类型的压缩
                string strSourcePhysic = TRPOP.Common.RequestHelper.GetMapPath(strSource);
                if (SYSConfig.Mobile_IsMobile && FileUtil.IsExist(strSourcePhysic))
                {
                    string strNewPath = strSourcePhysic.Insert(strSourcePhysic.LastIndexOf("."), SYSConfig.Mobile_ExtName);
                    using (System.IO.StreamReader strmReader = new System.IO.StreamReader(strSourcePhysic))
                    {
                        if (CKFinder.Connector.ImageTools.ResizeImage(strSourcePhysic, strNewPath, SYSConfig.Mobile_MaxWidth, SYSConfig.Mobile_MaxHeight, true, 80))
                        {
                            oDicSource[strSource].Add(ImgType.ImgResourceType.Iphone, strNormalURL.Insert(strNormalURL.LastIndexOf("."), SYSConfig.Mobile_ExtName));
                        }
                        else
                        {
                            oDicSource[strSource].Add(ImgType.ImgResourceType.Iphone, strNormalURL);
                        }
                    }
                }
            }
        }
        #endregion

        #region 信息内容 img标签处理
        private static Regex[] oRegexForImg = {
                                                  new Regex(string.Format(@"[<]img[^>]+?(?<scale>style[=][{0}][\s+\S+]+?[{0}])","\""),  RegexOptions.IgnoreCase),
                                                  new Regex(string.Format(@"[<]img[^>]+?(?<scale>(width|height)[=][{0}]\S+[{0}]([^>]+?(width|height)[=][{0}]\S+[{0}]){0,1})","\""),  RegexOptions.IgnoreCase)//需要去掉"
                                              };
        /// <summary>
        /// 检测内容里的图片，取消掉长宽限制
        /// </summary>
        /// <param name="strContent"></param>
        /// <param name="oImgResourceType"></param>
        /// <returns></returns>
        public string CheckContentImg(string strContent, ImgType.ImgResourceType oImgResourceType)
        {
            string strReturn = strContent;

            //如果PC版，则做任何处理
            if (oImgResourceType == ImgType.ImgResourceType.Normal)
                return strReturn;

            foreach (Regex oRegexTemp in oRegexForImg)
            {
                foreach (Match oMatch in oRegexTemp.Matches(strReturn))
                {
                    if (oMatch.Success && oMatch.Groups["scale"].Value.IsEmpty() == false)
                    {
                        strReturn = strReturn.Replace(oMatch.Value, oMatch.Value.Replace(oMatch.Groups["scale"].Value, string.Empty));
                    }
                }
            }

            return strReturn;
        }
        #endregion

    }
}
